package com.krmes.mes;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.krmes.mes.adapter.groupSelectAdapter;
import com.krmes.mes.app.AppContext;
import com.krmes.mes.bean.taskData;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.Header;

public class GroupSelectActivity extends Activity implements View.OnClickListener {
    private ListView listView;
    private groupSelectAdapter listViewAdapter;
    private String _id;
    private String  _fun;
    private Button btn_check_group;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_groupselect);
        this.listView = (ListView) this.findViewById(R.id.lv_data_sel);
        this.btn_check_group = (Button) this.findViewById(R.id.btn_check_group);
        this.btn_check_group.setOnClickListener(this);
        Bundle bundle = getIntent().getExtras();
        _id = bundle.getString("result");
        _fun = bundle.getString("result2");
        initListView();
    }

    private void initListView() {

        final ArrayList list = new ArrayList();
        if (_fun.equals("1")) {//开工
            ServerApi.getByGroupIdStart(_id, AppContext.loginCode, new JsonHttpResponseHandler() {
                public void onFailure(int pInt, Header[] pArrayOfHeader, String pString, Throwable pThrowable) {
                    AppContext.showToast(pThrowable.getMessage());
                    Intent intent = new Intent();
                    intent.putExtra("data", "12");
                    GroupSelectActivity.this.setResult(12, intent);
                }

                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    String jsonString = response.optString("data");
                    Gson gson = new Gson();
                    JsonParser jsonParser = new JsonParser();
                    JsonArray array = jsonParser.parse(jsonString).getAsJsonArray();
                    List<taskData> data = new ArrayList<taskData>();
                    for (JsonElement element : array) {
                        taskData t = gson.fromJson(element, taskData.class);
                        data.add(t);
                    }
                    if (data != null&& data.size()>0) {
                        for (int i = 0; i < data.size(); i++) {
                            Map<String, Object> map = new HashMap();
                            map.put("productname", data.get(i).getProductname());
                            map.put("keyfield", data.get(i).getKeyfield());
                            map.put("opdesc", data.get(i).getDptask());//data.get(i).getOpdesc());
                            map.put("sure", data.get(i).getIsstart());
                            list.add(map);
                        }
                        GroupSelectActivity.this.listViewAdapter = new groupSelectAdapter(GroupSelectActivity.this, list);
                        GroupSelectActivity.this.listView.setAdapter(listViewAdapter);
                        //GroupSelectActivity.this.setResult(11);
                        Intent intent = new Intent();
                        intent.putExtra("data", "11");
                        GroupSelectActivity.this.setResult(11, intent);

                    } else {
                        AppContext.showToast("没有符合的数据!");
                        this.onFinish();
                    }
                }

            });
        }else if (_fun.equals("2")) {//完工
            ServerApi.getByGroupIdEnd(_id, AppContext.loginCode,new JsonHttpResponseHandler(){
                @Override
                public void onFailure(int pInt, Header[] pArrayOfHeader, String pString, Throwable pThrowable) {
                    AppContext.showToast(pThrowable.getMessage());
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    String jsonString = response.optString("data");
                    Gson gson = new Gson();
                    JsonParser jsonParser = new JsonParser();
                    JsonArray array = jsonParser.parse(jsonString).getAsJsonArray();
                    List<taskData> data = new ArrayList<taskData>();
                    for (JsonElement element : array) {
                        taskData t = gson.fromJson(element, taskData.class);
                        data.add(t);
                    }
                    if (data != null&& data.size()>0) {
                        for (int i = 0; i < data.size(); i++) {
                            Map<String, Object> map = new HashMap();
                            map.put("productname", data.get(i).getProductname());
                            map.put("keyfield", data.get(i).getKeyfield());
                            map.put("opdesc",data.get(i).getDptask());// data.get(i).getOpdesc());
                            map.put("sure", data.get(i).getIsstart());
                            list.add(map);
                        }
                        GroupSelectActivity.this.listViewAdapter = new groupSelectAdapter(GroupSelectActivity.this, list);
                        GroupSelectActivity.this.listView.setAdapter(listViewAdapter);


                    } else {
                        AppContext.showToast("没有符合的数据!");
                        this.onFinish();
                    }
                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.btn_check_group:
                HashMap<Integer, Boolean> state =listViewAdapter.state;
                if (_fun.equals("1")) { //开工
                    for(int j=0;j<listViewAdapter.getCount();j++){
                        System.out.println("state.get("+j+")=="+state.get(j));
                        if(state.get(j)!=null){
                            @SuppressWarnings("unchecked")
                            HashMap<String, Object> map=(HashMap<String, Object>) listViewAdapter.getItem(j);
                            String _keyfield=map.get("keyfield").toString();
                            ServerApi.start(_keyfield, AppContext.loginCode, 1, new JsonHttpResponseHandler() {
                                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                                    AppContext.showToast(throwable.getMessage());
                                }

                                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                                    try {
                                        int i = response.getInt("ret_code");
                                        if (i == 0) {
                                            AppContext.showToast(response.getString("data")+"开工成功!");
                                            return;
                                        }else{
                                            AppContext.showToast(response.getString("data")+"开工不成功!");
                                            return;
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        }
                    }
                }else if (_fun.equals("2")) { //完工
                    for(int j=0;j<listViewAdapter.getCount();j++){
                        System.out.println("state.get("+j+")=="+state.get(j));
                        if(state.get(j)!=null){
                            @SuppressWarnings("unchecked")
                            HashMap<String, Object> map=(HashMap<String, Object>) listViewAdapter.getItem(j);
                            String _keyfield=map.get("keyfield").toString();
                            ServerApi.complete(_keyfield, AppContext.loginCode, 0x1, new JsonHttpResponseHandler() {

                                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                                    AppContext.showToast(throwable.getMessage());
                                }

                                public void onSuccess(int statusCode, Header[] headers, JSONObject response){
                                    try {
                                        if (response.getInt("ret_code") == 0) {
                                            AppContext.showToast(response.getString("data")+"完工成功!");
                                            return;
                                        }else{
                                            AppContext.showToast(response.getString("data")+"完工不成功!");
                                            return;
                                        }
                                    }catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        }
                    }
                }
                this.finish();
                break;
        }
    }
}
